//
//  GRLocationManager.m
//  YC_GRice
//
//  Created by LiuFeng on 2018/7/13.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRLocationManager.h"
#import <AMapFoundationKit/AMapFoundationKit.h>


@interface GRLocationManager () <AMapSearchDelegate, AMapLocationManagerDelegate>
{
    BOOL isLocationFinish;
    CLLocationCoordinate2D currentCoordinate;
}
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) AMapSearchAPI *aMapSearch;

@end

@implementation GRLocationManager

+ (instancetype)defaultManager {
    static GRLocationManager *location = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        location = [[GRLocationManager alloc] init];
    });
    
    return location;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [AMapServices sharedServices].apiKey = AMAPKEY;

        self.aMapSearch = [[AMapSearchAPI alloc] init];
        self.aMapSearch.delegate = self;
        
        self.locationManager = [[AMapLocationManager alloc] init];
        self.locationManager.delegate = self;
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
        
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"CityList" ofType:@"plist"];
        self.cityDictionary = [NSDictionary dictionaryWithContentsOfFile:filePath];
        self.letterKeys      = [self.cityDictionary.allKeys sortedArrayUsingSelector:@selector(compare:)];
    }
    return self;
}

- (void)startUpdatingLocation {
    isLocationFinish = NO;
    [self.locationManager startUpdatingLocation];
}



/**
 周围搜索
 */
-(void)poiAroundSearch:(CLLocationCoordinate2D)coordinate {
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location             = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    request.requireExtension = YES;
    request.radius               = 500;
    [self.aMapSearch AMapPOIAroundSearch:request];
}

/**
 关键字搜索
 */
- (void)poiKeyWord:(NSString *)keyword city:(NSString *)city {
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    request.city                  = city;
    request.keywords           = keyword;
    request.requireExtension = YES;
    [self.aMapSearch AMapPOIKeywordsSearch:request];
}


/**
 逆地理搜索请求

 @param coordinate 搜索中心点
 */
- (void)poiRegeocodeSearch:(CLLocationCoordinate2D )coordinate {
    AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    request.requireExtension = YES;
    [self.aMapSearch AMapReGoecodeSearch:request];
}

#pragma Mark  ---------  AMapLocationManagerDelegate  -------------
-(void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode {
    self.coordinate        = location.coordinate;
    self.currentLocation = location.coordinate;
    [self.locationManager stopUpdatingLocation];
    if (!isLocationFinish) {
        [self poiRegeocodeSearch:location.coordinate];
        isLocationFinish = YES;
    }
}


/**
 逆地理编码请求结果：用户当前所处位置
 */
-(void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response {
    if (response.regeocode != nil) {
        [self.locationManager stopUpdatingLocation];
        NSLog(@"onReGeocodeSearchDone --- regeocode = %@, location = %@\n",response.regeocode.formattedAddress, request.location);
        self.city                   = [response.regeocode.addressComponent.city stringByReplacingOccurrencesOfString:@"市" withString:@""];
        self.adcode               = response.regeocode.addressComponent.adcode;
        if (response.regeocode.pois.count > 0) {
            self.currentpoi       = response.regeocode.pois.firstObject;
            self.currentpoi.city = self.city;
            self.currentpoi.adcode  = self.adcode;
            self.currentpoi.location = request.location;
            [[NSNotificationCenter defaultCenter] postNotificationName:GRDidFinishLocationNotification object:self userInfo:@{LocationKey : self.currentpoi, DragMapKey : @(NO)}];
        }
    }
}


/**
 附近搜索/关键字搜索 结果
 */
-(void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {
    if (response.pois.count > 0) {
        if (self.completionHandler) {
            // 定位：用户搜索位置
            BOOL isAround = [request isKindOfClass:[AMapPOIAroundSearchRequest class]] ? YES : NO;
            self.completionHandler(response.pois, isAround);
        }else {
            // 首页：拖动地图
            AMapPOI *poi   = response.pois.firstObject;
            self.city          = [poi.city stringByReplacingOccurrencesOfString:@"市" withString:@""];
            self.adcode      = poi.adcode;
            self.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
            poi.location      = [(AMapPOIAroundSearchRequest *)request location];
            [[NSNotificationCenter defaultCenter] postNotificationName:GRDidFinishLocationNotification object:self userInfo:@{LocationKey : poi, DragMapKey : @(YES)}];
        }
    }
}

-(void)amapLocationManager:(AMapLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self.locationManager startUpdatingLocation];
    }else {
        [self.locationManager stopUpdatingLocation];
    }
}

-(void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error {
    if (error.code == 1806) {
        [[NSNotificationCenter defaultCenter] postNotificationName:GRDidLocationFailureNotification object:self userInfo:nil];
    }
    NSLog(@"搜索失败:%@",error);
}

- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    [[NSNotificationCenter defaultCenter] postNotificationName:GRDidLocationFailureNotification object:self userInfo:nil];
    NSLog(@"定位失败:%@",error);
}



@end
